<template>
  <div>
    <!-- title -->
    <PageTitle>
      {{ $t("menu.M_10400204") }}
    </PageTitle>
    <!--    <el-tabs  >
      <el-tab-pane :label="$t('operator.createOperator')" name="first" />
      <el-tab-pane :label="$t('operator.createDemoOperator')" name="second" />
    </el-tabs>-->
    <el-card
      shadow="never"
      :body-style="{ padding: '0px' }"
      :page-size="pageSize"
      :total="rows"
      :current-page="pageNo"
      @current-change="currentChangeHandle"
    >
      <el-form class="p-4" inline :model="dataForm">
        <!--      <el-form-item :label="$t('operator.name')">
                  <el-input v-model="dataForm.name" :placeholder="$t('operator.name')" clearable></el-input>
                </el-form-item>-->
        <el-form-item>
          <el-input
            v-model="dataForm.operatorName"
            maxlength="100"
            style="width: 270px"
            :placeholder="$t('operator.condition')"
            clearable
            @blur="() => (dataForm.operatorName = dataForm.operatorName.trim())"
            @keyup.enter.native="getDataList((pageNo = 1))"
          />
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="dataForm.operatorStatus"
            clearable
            :placeholder="$t('operator.status')"
          >
            <el-option
              v-for="item in $t('operator.audit_status_list')"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="w-8" @click="getDataList((pageNo = 1))">
            <svg-icon icon-class="search" />
          </el-button>
        </el-form-item>
        <!--        <el-form-item>
          <el-button
            v-if="isAuth('10400202.MANAGE') && !this.demoAccountVisible"
            type="primary"
            class="p-1.5 align-middle"
            @click="createOperator"
          >
            <svg-icon icon-class="plus" />
          </el-button>
          <el-button
            v-if="isAuth('10400202.MANAGE') && this.demoAccountVisible"
            type="primary"
            class="p-1.5 align-middle"
            @click="createDemoOperator"
          >
            <svg-icon icon-class="plus" />
          </el-button>
        </el-form-item>-->

        <el-form-item>
          <el-button
            v-if="isAuth('10400204.MANAGE')"
            type="primary"
            class="w-8"
            @click="createLevelEmail"
          >
            <svg-icon icon-class="Message" />
          </el-button>
        </el-form-item>
        <!--        <el-form-item>
          <el-button
            type="primary"
            class="p-1.5 align-middle"
            @click="exportOperator"
          >
            <svg-icon icon-class="download" />
&lt;!&ndash;            <svg-icon icon-class="email" />&ndash;&gt;
          </el-button>
        </el-form-item>-->
        <el-form-item style="float: right">
          <el-button style="border: none" type="primary" class="w-8">
            <table-column-filter
              :list="settingList"
              :default-setting="defaultSettings"
              v-model:settings="settings"
              domain="operator.table"
            />
          </el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="dataListLoading" :data="dataList" stripe>
        <el-table-column prop="operatorName" :label="$t('operator.name')">
          <template v-slot="scope">
            <div class="cursor-pointer" @click="showDetailHandle(scope.row)">
              {{ scope.row.operatorName }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-if="showHeader('LINKMAN')"
          key="linkMan"
          prop="linkMan"
          :label="$t('operator.linkman')"
        />
        <el-table-column
          v-if="showHeader('CN')"
          key="caCn"
          prop="caCn"
          min-width="100"
          :label="$t('operator.subject_cn')"
        />
        <el-table-column
          v-if="showHeader('ISSUER_CN')"
          key="issuerCn"
          prop="issuerCn"
          min-width="100"
          :label="$t('operator.issuer_cn')"
        />
        <el-table-column
          v-if="showHeader('COUNTRY')"
          key="countryCode"
          prop="countryCode"
          :formatter="formatCountry"
          :label="$t('operator.country')"
        />
        <el-table-column prop="status" width="200px" :label="$t('operator.status')">
          <template v-slot="scope">
            <el-tag v-if="scope.row.status === 2" size="small" type="warning"
              >{{ $t("operator.pendingReview") }}
            </el-tag>
            <el-tag v-if="scope.row.status === 1" size="small">{{
              $t("operator.normal")
            }}</el-tag>
            <el-tag v-if="scope.row.status === 0" size="small" type="info">{{
              $t("operator.locked")
            }}</el-tag>
            <el-tag v-if="scope.row.status === 3" size="small" type="danger"
              >{{ $t("operator.reject") }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          v-if="showHeader('CRETIME')"
          key="creTime"
          prop="creTime"
          :label="$t('common.createTime')"
        >
          <template v-slot="scope">
            <div :title="timeFilter(scope.row.creTime)">
              {{ dateFilter(scope.row.creTime) }}
              {{ scope.row.creTime ? "" : "-" }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="levelCode" width="200px" :label="$t('operator.level')">
          <template v-slot="scope">
            <el-tooltip
              v-if="scope.row.levelName && scope.row.levelName.length > 12"
              class="item"
              effect="dark"
              :content="$t('system_menu.level_name') + ': ' + scope.row.levelName"
              placement="top"
            >
              <el-tag size="small">
                {{ expirationHandler(scope.row.levelName, scope.row.levelExpireTime) }}
              </el-tag>
            </el-tooltip>
            <el-tag
              v-if="!scope.row.levelName || scope.row.levelName.length <= 12"
              size="small"
            >
              {{ expirationHandler(scope.row.levelName, scope.row.levelExpireTime) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column width="75px">
          <template v-slot="scope">
            <!--          <el-button type="warning" @click="leverChangeHandle(scope.row)">{{$t('operator.lever')}}</el-button>-->
            <el-dropdown trigger="click">
              <el-button text class="w-8">
                <svg-icon icon-class="MoreFilled" />
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="showDetailHandle(scope.row)">
                    <svg-icon icon-class="View" />
                    {{ $t("common.detail") }}
                  </el-dropdown-item>
                  <el-dropdown-item
                    @click="checkOperatorHandle(scope.row)"
                    v-if="scope.row.status == 2 && isAuth('10400204.MANAGE')"
                  >
                    <svg-icon icon-class="User" />
                    {{ $t("operator.checkBtn") }}
                  </el-dropdown-item>
                  <el-dropdown-item
                    @click="deleteHandle(scope.row)"
                    v-if="scope.row.status == 3 && isAuth('10400204.MANAGE')"
                  >
                    <svg-icon icon-class="Delete" />
                    {{ $t("common.deleteBtn") }}
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>

            <!-- <el-tooltip
              class="item"
              effect="dark"
              :content="$t('common.detail')"
              placement="top"
            >
              <el-button text style="color: #8c939d" @click="showDetailHandle(scope.row)">
                <svg-icon icon-class="View" />
              </el-button>
            </el-tooltip> -->

            <!-- <el-tooltip class="item" effect="dark" :content="$t('operator.addResourceBtn')" placement="top">
              <el-button
                v-if="scope.row.status == 1"
                style="color: #8c939d"
                icon="el-icon-set-up"
                type="text"
                @click="addLicenseHandle(scope.row)"
              />
            </el-tooltip> -->

            <!-- <el-tooltip
              class="item"
              effect="dark"
              :content="$t('operator.checkBtn')"
              placement="top"
            >
              <el-button
                v-if="scope.row.status == 2 && isAuth('10400204.MANAGE')"
                style="color: var(--color-warning)"
                text
                @click="checkOperatorHandle(scope.row)"
              >
                <svg-icon icon-class="User" />
              </el-button>
            </el-tooltip> -->

            <!-- <el-tooltip class="item" effect="dark" :content="$t('operator.managementBtn')" placement="top">
              <el-button icon="el-icon-message" style="color: #8c939d" type="text" @click="reset(scope.row.operatorId, scope.row.operatorType)" />
            </el-tooltip> -->

            <!-- <el-tooltip
              class="item"
              effect="dark"
              :content="$t('operator.permissionsBtn')"
              placement="top"
            >
              <el-button v-if="scope.row.status == 1" type="text" style="color: #8c939d" icon="el-icon-setting" @click="blackListHandle(scope.row)" />
            </el-tooltip> -->
            <!-- <el-tooltip
              v-if="isAuth('10400204.MANAGE')"
              class="item"
              effect="dark"
              :content="$t('common.deleteBtn')"
              placement="top"
            >
              <el-button
                v-if="scope.row.status == 3 && isAuth('10400204.MANAGE')"
                text
                class="w-8"
                style="color: var(--color-danger)"
                @click="deleteHandle(scope.row)"
              >
                <svg-icon icon-class="Delete" />
              </el-button>
            </el-tooltip> -->
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <operator-detail
      v-if="operatorDetailVisible"
      ref="operatorDetail"
      @close="operatorDetailVisible = false"
    />
    <check-operator
      v-model="checkOperatorVisible"
      ref="checkOperator"
      @refreshDataList="getDataList"
    />
    <business
      v-if="addBusinessVisible"
      ref="business"
      @refreshDataList="getDataList"
      @close="addBusinessVisible = false"
    />
    <change-level
      v-if="changeLevelVisible"
      ref="changeLevel"
      @refreshDataList="getDataList"
      @close="changeLevelVisible = false"
    />
    <add-operator
      v-if="addOperatorVisible"
      ref="addOperator"
      @refreshDataList="getDataList"
      @close="addOperatorVisible = false"
    />
    <add-demo-operator
      v-if="addDemoOperatorVisible"
      ref="addDemoOperator"
      @refreshDataList="getDataList"
      @close="addDemoOperatorVisible = false"
    />
    <permissions
      v-if="permissionsVisible"
      ref="permissions"
      @refreshDataList="getDataList"
      @close="permissions = false"
    />
    <resetpw-operator
      v-if="resetpwOperatorVisible"
      ref="resetpwOperator"
      @refreshDataList="getDataList"
      @close="resetpwOperatorVisible = false"
    />
    <bind-operator v-model="addLevelEmailVisible" ref="addLevelEmail" />
  </div>
</template>

<script>
import { timeFilter, dateFilter } from "@/filters/index";
import TableColumnFilter from "@/components/page-setting/table-column-filter";

import { formatDate } from "@/utils/formatDate";
import { formatCountry } from "@/utils/formatCountry";
import {
  operatorList,
  deleteOperator,
  operatorLevelList,
  // exportOperatorInfo,
  auditOperatorList,
} from "@/api/operator";
import OperatorDetail from "./components/operator-detail";
import CheckOperator from "./components/check-operator";
import ResetpwOperator from "./components/resetpw-operator";
import Business from "./components/add-business";
import ChangeLevel from "./components/change-level";
import AddOperator from "./components/add-operator";
import AddDemoOperator from "./components/add-demo-operator";
import Permissions from "./components/permissions";
import BindOperator from "./components/expired-level-email";
import { isAuth } from "@/utils";
import PageTitle from "@/components/PageTitle/index.vue";
export default {
  name: "OperatorAudit",
  components: {
    OperatorDetail,
    CheckOperator,
    Business,
    ChangeLevel,
    AddOperator,
    AddDemoOperator,
    Permissions,
    ResetpwOperator,
    BindOperator,
    TableColumnFilter,
    PageTitle,
  },
  data() {
    return {
      dataForm: {
        operatorName: "",
        operatorStatus: null,
      },
      settings: {
        conditions: [],
        columns: [],
      },
      activeName: "first",
      operatorDetailVisible: false,
      checkOperatorVisible: false,
      addBusinessVisible: false,
      changeLevelVisible: false,
      addOperatorVisible: false,
      addDemoOperatorVisible: false,
      addLevelEmailVisible: false,
      updateMapVisible: false,
      permissionsVisible: false,
      resetpwOperatorVisible: false,

      cardBindBankId: 0,
      dataList: [],
      pageNo: 1,
      pageSize: 10,
      rows: 0,
      dataListLoading: false,
      orderListLoading: false,
      agreementShowVisible: false,
      curOperator: {},
      operatorLeverList: [],
      demoAccountVisible: false,
    };
  },
  computed: {
    settingList() {
      return {
        columns: [
          {
            title: this.$t("operator.linkman"),
            code: "LINKMAN",
          },
          {
            title: this.$t("operator.subject_cn"),
            code: "CN",
          },
          {
            title: this.$t("operator.issuer_cn"),
            code: "ISSUER_CN",
          },
          {
            title: this.$t("operator.country"),
            code: "COUNTRY",
          },
          {
            title: this.$t("common.createTime"),
            code: "CRETIME",
          },
        ],
      };
    },
    defaultSettings() {
      return {
        columns: [
          "LINKMAN",
          // this.$t('common.online'),
          "CN",
        ],
      };
    },
  },
  mounted() {
    this.$store.commit("app/ADD_KEEP_ALIVE_LIST", "OperatorAudit");
    this.init();
  },
  beforeRouteLeave(to, from, next) {
    if (to.name !== "audit-Info") {
      this.$store.commit("app/REMOVE_KEEP_ALIVE_LIST", "OperatorAudit");
    }
    next();
  },
  methods: {
    timeFilter,
    dateFilter,
    async init() {
      await this.getDataList();
      await this.getOperatorLevelLsit();
    },
    showHeader(label) {
      var list = this.settings["columns"];
      return list ? list.includes(label) : false;
    },
    showFormItem(label) {
      var list = this.settings["conditions"];
      return list ? list.includes(label) : false;
    },
    /* reset(operatorId, operatorType) {
      this.resetpwOperatorVisible = true
      this.$nextTick(() => {
        this.$refs.resetpwOperator.init(operatorId, operatorType)
      })
    },*/
    /* exportOperator() {
      this.$confirm(this.$t('operator.export_operator_info_confirm'), this.$t('operator.export_operator_info'), {
        confirmButtonText: this.$t('common.confirm'),
        cancelButtonText: this.$t('common.cancel'),
        type: 'warning'
      }).then(() => {
        window.location.href = import.meta.env.VITE_APP_BASE_API +
              '/online/management/admin/operator/export?WEB-TOKEN=' +
              getToken() + '&timezone=' + Intl.DateTimeFormat().resolvedOptions().timeZone + '&pageNo=1&pageSize=10&operatorType=1' + '&operatorName=' + this.dataForm.operatorName
      }).catch(() => {
      })
    },*/
    currentOperator(row) {
      this.curOperator = row;
    },
    batchOperate(command) {
      this.changeLevelVisible = true;
      this.$nextTick(() => {
        this.$refs.changeLevel.init(command, this.curOperator.operatorId);
      });
    },
    // 获取数据列表
    getDataList() {
      console.log(this.activeName);
      this.dataListLoading = true;
      const params = {
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        operatorName: this.dataForm.operatorName,
        operatorStatus: this.dataForm.operatorStatus,
        operatorType: 1,
      };
      auditOperatorList(params)
        .then((data) => {
          this.dataList = data.data;
          this.rows = data.rows;
          this.dataListLoading = false;
        })
        .catch((e) => {
          this.dataListLoading = false;
          this.$confirmError(e);
          // this.$message.error(e.message)
          console.log(`err:${JSON.stringify(e)}`);
        });
    },
    deleteHandle(row) {
      this.$confirm(this.$t("operator.deleteConfirm"), "", {
        confirmButtonText: this.$t("common.confirm"),
        cancelButtonText: this.$t("common.cancel"),
        type: "warning",
      }).then(() => {
        this.$confirm(this.$t("operator.deleteConfirm1"), "", {
          confirmButtonText: this.$t("common.confirm"),
          cancelButtonText: this.$t("common.cancel"),
          type: "warning",
        }).then(() => {
          this.$confirm(this.$t("operator.deleteConfirm2"), "", {
            confirmButtonText: this.$t("common.confirm"),
            cancelButtonText: this.$t("common.cancel"),
            type: "warning",
          }).then(() => {
            deleteOperator(row.operatorId)
              .then((data) => {
                this.$message({
                  type: "success",
                  message: this.$t("common.success"),
                });
                this.getDataList();
              })
              .catch((e) => {
                this.$confirmError(e);
              });
          });
        });
      });
      console.log(row);
    },

    getOperatorLevelLsit() {
      const param = {
        characterCode: "OPERATOR",
      };
      operatorLevelList(param)
        .then((data) => {
          this.operatorLevelList = data;
          console.log(this.operatorLevelList);
        })
        .catch((e) => {
          this.$confirmError(e);
        });
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageNo = 1;
      this.getDataList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageNo = val;
      this.getDataList();
    },
    showDetailHandle(row) {
      localStorage.setItem("operator-info", JSON.stringify(row));
      this.$router.push({
        path: `/operator/audit-detail/${row.operatorId}`,
      });
      // this.operatorDetailVisible = true
      // this.$nextTick(() => {
      //   this.$refs.operatorDetail.init(id)
      // })
    },
    checkOperatorHandle(row) {
      console.log(row);
      /* if (row.operatorType === 'DEMO') {
        // 服务调用失败的情况，才会出现
        this.checkDemoOperatorVisible = true
        this.$nextTick(() => {
          this.$refs.checkDemoOperator.init(row)
        })
      } else {
        this.checkOperatorVisible = true
        this.$nextTick(() => {
          this.$refs.checkOperator.init(row)
        })
      } */

      this.checkOperatorVisible = true;
      this.$nextTick(() => {
        this.$refs.checkOperator.init(row);
      });
    },
    addLicenseHandle(row) {
      // this.$router.push(
      //   {
      //     path: `/operator/operator-detail`,
      //     query: {
      //       operatorId: row.operatorId,
      //       operatorType: row.operatorType
      //     }
      //   }
      // )
      this.addBusinessVisible = true;
      this.$nextTick(() => {
        this.$refs.business.init(row);
      });
    },
    resetMapHandle(row) {
      this.updateMapVisible = true;
      this.$nextTick(() => {
        this.$refs.updateMap.init(row);
      });
    },
    blackListHandle(row) {
      this.permissionsVisible = true;
      this.$nextTick(() => {
        this.$refs.permissions.init(row);
      });
    },
    formatDate(cellValue, fmt) {
      cellValue = new Date(cellValue).valueOf();
      return formatDate(cellValue, fmt);
    },
    formatCountry(row, column, cellValue, index) {
      return formatCountry(cellValue);
    },
    expirationHandler(Name, levelExpirationTime) {
      // eslint-disable-next-line no-unused-vars
      if (!Name) {
        Name = "-";
      }
      let levelName = Name;
      if (Name.length > 11) {
        levelName = Name.slice(0, 11) + "...";
      }
      // if (levelCode === 'STANDARD_LEVEL') {
      //   levelName = this.$t('operator.level_list[0].label')
      // } else if (levelCode === 'ENTERPRISE_LEVEL') {
      //   levelName = this.$t('operator.level_list[1].label')
      // }
      console.log(levelExpirationTime);
      if (!levelExpirationTime || levelExpirationTime === undefined) {
        return levelName + " | " + this.$t("operator.leverExpireForever");
      }
      var date = formatDate(levelExpirationTime, "YYYY-MM-DD");
      return levelName + " | " + date;
    },
    cellStyle({ row, column, rowIndex, columnIndex }) {
      let value = row[column.property];
      if (value != null) {
        if (column.property === "creTime") {
          value = this.formatDate(row[column.property], "YYYY-MM-DD");
        }
        if (column.property === "countryCode") {
          value = formatCountry(row[column.property]);
        }
        if (value.length * 13 > column.width) {
          return "font-size:" + (column.width * 0.95) / value.length + "px";
        }
      }
      // console.log(rowIndex + ':' + JSON.stringify(row))
      //  console.log(columnIndex + ':' + JSON.stringify(column))
    },
    /*    createOperator() {
      this.addOperatorVisible = true
      this.$nextTick(() => {
        this.$refs.addOperator.init()
      })
    },
    createDemoOperator() {
      this.addDemoOperatorVisible = true
      this.$nextTick(() => {
        this.$refs.addDemoOperator.init()
      })
    },*/
    /* handleClick(tab, event) {
      if (tab.name === 'second') {
        this.demoAccountVisible = true
      } else if (tab.name === 'first') {
        this.demoAccountVisible = false
      }
      this.getDataList()
    },*/
    createLevelEmail() {
      this.addLevelEmailVisible = true;
      this.$nextTick(() => {
        this.$refs.addLevelEmail.init();
      });
    },
    isAuth,
  },
};
</script>
<style lang="scss" scope>
.app-container {
  padding: 20px;
  background: #ffffff;
  border-radius: 8px;

  &--border-none {
    border-radius: 0;
  }
}
</style>
